<template>
<div>
    <selectArea
    :homeInfo="homeId"
    homeType="focus"
    :hasDevice="hasDevice"
    @on-delete-home="handleDeleteHome"
    @on-edit-info="ok"
    @on-change="handleAreaChange"></selectArea>

    <Card class="no-border-card" style="margin-top:24px;">
        <p slot="title">
            房间信息
        </p>
        <div class="c-extra-btn-group" slot="extra">
            <Button type="primary"
                class="c-extra-btn"
                v-if="homeId"
                @click="isAddFloorVisible=true">
                新增楼层
            </Button>
            <Button
                type="primary"
                class="c-extra-btn"
                v-if="homeId"
                @click="isAddRoomVisible=true">
                新增房间
            </Button>
        </div>

        <Row class="range" :gutter="20" v-if="!homeId">
            <Col span="6">
                <InputNumber style="width:100%" :min="1" :max="99" v-model="building" placeholder="楼栋数量(可选，默认1)"></InputNumber>
            </Col>

            <Col span="6">
                <InputNumber style="width:100%" :min="1" :max="99" v-model="floor" placeholder="楼层数量"></InputNumber>
            </Col>

            <Col span="6">
                <InputNumber style="width:100%" :min="1" :max="99" v-model="room" placeholder="每层房间数量"></InputNumber>
            </Col>

            <Col span="6">
                <InputNumber style="width:100%" v-model="startFloor" placeholder="起始楼层(可选，默认1)"></InputNumber>
            </Col>
        </Row>

        <Row :gutter="32" v-if="!homeId" style="margin-bottom:20px;">

            <Col span="8" style="padding-right: 10px;">
                <Checkbox v-model="modal1" style="height:32px;line-height:32px;">去除指定楼层</Checkbox>
                <Input v-model="passFloor" :disabled="!modal1" placeholder="填入楼层数字，用空格隔开"></Input>
            </Col>

      <!--  <Col span="8">
                <Checkbox v-model="modal2" style="height:32px;line-height:32px;">去除含有以下数字的房间</Checkbox>
                <Input v-model="passRoom" :disabled="!modal2" placeholder="填入楼层数字，用空格隔开"></Input>
            </Col> -->

            <!-- <Col span="8">
                <Checkbox v-model="modal3" style="height:32px;line-height:32px;">批量分拆房间</Checkbox>
                <InputNumber
                    style="width:100%"
                    :min="1"
                    :max="10"
                    v-model="roomMiddle"
                    placeholder="单套房间数量"
                    :disabled="!modal3"></InputNumber>
            </Col> -->

            <Col span="8" style="padding-top:32px;padding-left:0;">
                <Button type="primary" @click="addHouse()">生成房间</Button>
                <Button type="primary" @click="delHouse()" style="margin-left:5px;">清空房间</Button>
            </Col>
        </Row>

        <!-- 批量修改楼层 -->
        <Row :gutter="8" v-if="homeId" style="margin-bottom:15px;">
            <Col span="24" class="clear-fix">
                <!-- <Button type="ghost"  @click="isAddFloorVisible=true">新增楼层</Button>
                <Button type="ghost" @click="isAddRoomVisible=true">新增房间</Button> -->
                <Select v-model="changeFloor" placeholder="选择楼层" style="width:200px;margin-right:4px;">
                    <Option
                    v-for="item in allFloors"
                    :value="item"
                    v-if="item != 0"
                    :key="item+'floor'">{{ '修改所选房间楼层为 ' + item + ' 层' }}
                    </Option>
                </Select>
                <Button type="ghost" style="margin-right:4px;" @click="changeFloors">批量修改楼层</Button>
                <!-- <Button type="ghost" style="margin-right:4px;" @click="clearChangeFloors">清空所选房间</Button> -->
            </Col>
        </Row>

        <!-- 无分拆 -->
        <div
            v-for="(item,index) in floors"
            :key="'floor'+index"
            v-if="!hasRoomMiddle && !isSpecialHome"
            class="floor-item">

            <div class="flex-floor" style="min-height: 30px">
                <p >{{index}}层</p>
                <div class="margin-top-10" v-if="homeId">
                    <Poptip title="操作楼层">
                        <a href="javascript:;">编辑</a>
                        <div slot="content" style="padding:10px 0">
                            <i-button size="small" @click="handleEditFloor(index)">修改楼层</i-button>
                            <i-button size="small" @click="handleDeleteFloor(index)">删除</i-button>
                        </div>
                    </Poptip>
                </div>
                <!-- <div>
                    <Button type="error">删除楼层</Button>
                </div> -->
            </div>

            <Row class="flex-room" type="flex" :gutter="16">
                <Col
                    v-for="(room,indx) in item"
                    :key="'room'+indx"
                    span="6"
                    class="marginTopItem">

                    <Row class="room-item-wrapper">
                        <Col span="18" style="padding:0;">
                            <span class="f-room-box">
                                <span class="f-room-prepend" v-if="homeId">
                                    <input type="checkbox" v-model="room.isChangeFloor">
                                </span>
                                <span class="f-room-content"  v-if="homeId">
                                    <span>{{room.name}}</span>
                                </span>
                                <i-input
                                    v-if="!homeId"
                                    v-model="room.name"></i-input>
                                <span class="f-room-append" @click="handleDelete(room,index,indx)">
                                    <Icon class="del-room-icon" type="ios-close-empty" ></Icon>
                                </span>
                            </span>
                        </Col>

                        <Col span="6"  style="padding:0 0 0 10px;" >
                            <Button class="room-operate-btn" @click="handleEdit(room)" v-if="homeId">
                                修改
                            </Button>
                        </Col>
                    </Row>
                </Col>
            </Row>
        </div>

        <!-- 集散式列表 -->
        <div
            v-for="(floorData, floor) in floors"
            :key="'floor'+floor"
            v-if="!hasRoomMiddle && isSpecialHome"
            class="floor-item">

            <div class="flex-floor" style="min-height: 30px">
                <p>{{floor}}层</p>
            </div>

            <Row class="flex-room" type="flex" :gutter="16">
                <Col
                    v-for="(parentRoom, index) in floorData"
                    :key="'parentRoom'+index"
                    span="6">
                    <Row class="room-item-wrapper marginTopItem">
                        <Col span="18" style="padding:0;">
                            <div class="f-room-box">
                                <span class="f-room-prepend">
                                    <input type="checkbox" v-model="parentRoom.isChangeFloor">
                                </span>
                                <span class="f-room-content">
                                    <span>{{parentRoom.name}}</span>
                                </span>
                                <span
                                    class="f-room-append"
                                    v-if="!parentRoom.rooms || parentRoom.rooms.length === 0"
                                    @click="handleDelete(parentRoom,floor,index)">
                                    <Icon class="del-room-icon" type="ios-close-empty" ></Icon>
                                </span>
                                <div v-else class="f-room-append">
                                    <Poptip placement="top" width="300">
                                        <Icon type="chevron-right" style="padding:10px"></Icon>
                                        <div slot="content">
                                            <div
                                                style="margin: 15px;display:flex"
                                                v-for="(room,key) in parentRoom.rooms"
                                                :key="'room'+key">
                                                <span class="f-room-box" style="width:210px">
                                                    <span class="f-room-prepend no-border"></span>
                                                    <span class="f-room-content">
                                                        <span>{{room.name}}</span>
                                                    </span>
                                                    <span class="f-room-append" @click="handleDelete(room,floor,index,key)">
                                                        <Icon class="del-room-icon" type="ios-close-empty" ></Icon>
                                                    </span>
                                                </span>
                                                <Button class="margin-left-10" @click="handleEdit(room)">
                                                    修改
                                                </Button>
                                            </div>
                                        </div>
                                    </Poptip>
                                </div>
                            </div>
                        </Col>
                        <Col span="6" style="padding:0 0 0 5px;" >
                            <Button class="room-operate-btn"
                                @click="handleEdit(parentRoom)"
                                v-if="!parentRoom.rooms">
                                修改
                            </Button>
                        </Col>
                    </Row>

                </Col>
            </Row>
        </div>

        <!-- 添加房源 有分拆 -->
        <Row style="display:flex" v-for="(item,index) in floors" :key="'floor'+index" v-if="hasRoomMiddle" class="floor-item">

            <Col span="1" class="flex-floor">
                <p>{{index}}层</p>
            </Col>

            <Col span="23">
                <Row type="flex" v-for="(val,indx) in item" :key="'val'+indx" :class="{ marginTopItem:indx > 0 }">
                    <Col v-for="(room,idx) in val.rooms" :key="'room'+idx" span="6">
                        <Row style="margin-bottom:15px;" class="room-item-wrapper">
                            <Col span="18" style="padding:0;">
                                <Input v-model="room.name">
                                    <Icon class="del-room-icon" type="ios-close-empty" slot="append" @click="delTags(index,indx,idx,val)"></Icon>
                                </Input>
                            </Col>
                        </Row>
                    </Col>
                </Row>
            </Col>

        </Row>

    </Card>

    <Modal v-model="isAddRoomVisible " title="新增房间">
        <Form ref="addRoomForm" :model="formItem" :label-width="80" :show-message="false">
            <FormItem label="房间名称" prop="roomName">
                <Input v-model="formItem.roomName" placeholder="请输入房间名"/>
                <p>注: 如果要添加多个房间，可输入多个房间名，房间名以,号隔开,<br/>如: 房间1,房间2</p>
            </FormItem>
            <FormItem label="房间楼层" prop="roomFloor">
                <!-- <Input v-model="formItem.roomFloor" :maxlength="11" placeholder="请输入房间楼层"></Input> -->

                <Select v-model="formItem.roomFloor" placeholder="选择房间楼层">
                    <Option
                    v-for="item in allFloors"
                    :value="item"
                    v-if="item != 0"
                    :key="item+'floor'">{{ '新增房间到 ' + item + ' 层' }}
                    </Option>
                </Select>
            </FormItem>
            <div style="padding-left:80px;font-size:12px;">若房源用电公摊设置为按比例分摊，新增房间需设置分摊比例。</div>

        </Form>

        <div slot="footer">
            <Button type="text" size="large" @click="cancelAddRoom">取消</Button>
            <Button type="primary" size="large" @click="addRoom">确定</Button>
        </div>
    </Modal>

    <Modal v-model="isAddFloorVisible" title="新增楼层">
        <Form :label-width="80" :show-message="false">
            <FormItem label="房间楼层" prop="roomFloor">
                 <InputNumber style="width:100%" :min="1" :max="99" v-model="tempAddFloor" placeholder="请输入房间楼层"></InputNumber>
            </FormItem>
        </Form>

        <div slot="footer">
            <Button type="text" size="large" @click="cancelAddFloor">取消</Button>
            <Button type="primary" size="large" @click="actionAddFloor">确定</Button>
        </div>
    </Modal>

</div>
</template>

<script>
import util from '@/libs/util'
import { http, api } from '@/libs/http'
// import dataCenter from '@/libs/dataCenter';
import selectArea from '../selectArea'

export default {
  props: {
    homeId: ''
  },
  components: {
    selectArea
  },
  data () {
    return {
      isSpecialHome: false,
      isLoading: false,
      modal1: '',
      flag: true,
      floor: null,
      floors: {},
      startFloor: null,
      passFloor: null,
      passRoom: null,
      room: null,
      building: null,
      modal2: false,
      modal3: false,
      roomMiddle: null,
      hasRoomMiddle: false,
      tags: [],
      existedFloors: [],
      isAddRoomVisible: false,
      formItem: {
        roomName: '',
        roomFloor: ''
      },

      isAddFloorVisible: false,
      tempAddFloor: null,
      allFloors: [],
      changeFloor: '',
      hasDevice: false
    }
  },

  async mounted () {
    if (this.homeId) {
      await this.getAllFloors()
      this.getRooms(this.homeId.id)
    }
  },
  methods: {
    handleEdit (room) {
      let newName = room.name
      this.$Modal.confirm({
        loading: true,
        render: h => {
          return h('Input', {
            props: {
              value: newName,
              autofocus: true
            },
            on: {
              input: val => {
                newName = val
              }
            }
          })
        },
        onOk: () => {
          if (newName === '公区') {
            this.$Message.info('房间名不能为公区')
            this.$Modal.remove()
            return
          }
          if (newName === '') {
            this.$Message.info('房间名不能为空')
            this.$Modal.remove()
            return
          }
          this.doEdit(room, { room_name: newName })
        }
      })
    },
    doEdit (room, data) {
      http.request(this, api.room_update, [room.id], data, (res, err) => {
        this.$Modal.remove()
        if (err) {
          this.$Message.error('修改失败')
        } else {
          room.name = data.room_name
          this.$Message.success('修改成功')
        }
      })
    },
    handleDelete (room, parentIndex, index, specicalIndex) {
      if (this.homeId) {
        this.$Modal.confirm({
          title: '确定删除?',
          content: util.escapeHtml(`房间 ${room.name} 将会被删除`),
          loading: true,
          onOk: () => {
            this.doDeleteRoom(room, parentIndex, index, specicalIndex)
          }
        })
      } else {
        this.floors[parentIndex].splice(index, 1)
      }
    },
    doDeleteRoom (room, parentIndex, index, specicalIndex = undefined) {
      http.request(this, api.room_del, [room.id], null, (res, err) => {
        try {
          this.$Modal.remove()
          if (err || !res) {
            this.$Message.error('删除失败')
          } else {
            if (specicalIndex !== undefined) {
              // 集散式删除
              const parentRoom = this.floors[parentIndex][index]
              parentRoom.rooms.splice(specicalIndex, 1)
              // console.log(parentRoom);
              if (parentRoom.rooms.length === 0) {
                this.doDeleteRoom(parentRoom, parentIndex, index)
              }
            } else {
              this.floors[parentIndex].splice(index, 1)
            }
            this.$Message.success('删除成功')
          }
        } catch (err) {
          console.log(err)
        }
      })
    },
    handleAreaChange (areaInfo) {
      this.areaInfo = areaInfo
    },

    // 获取房源下的房间
    getRooms (id) {
      this.isLoading = true
      http.request(this, api.room_list, [id], { with_device: 1 }, (res, err) => {
        this.isLoading = false
        if (err || !res) {
          return
        }
        let flag = res.some(item => {
          return item.parent_ids.length > 1
        })

        if (flag) {
          this.genSepcialData(res)
        } else {
          let map = {}
          res.forEach(item => {
            if (item.room_type === 1) {
              map[item.floor] = []
            }
            if (item.devices.length) this.hasDevice = true
          })
          for (let k in map) {
            res.forEach(item => {
              if (k === item.floor && item.room_type === 1) {
                item.name = item.room_name
                map[k].push(item)
              }
            })

            map[k].sort((a, b) => {
              return a.name.localeCompare(b.name)
            })
          }
          // 去除没有一层 但是公区的是一层的数据
          for (let i in map) {
            if (map[i].length === 0) {
              // this.allFloors = this.allFloors.filter(floor => +floor !== +i)
              delete map[i]
            }
          }
          this.allFloors = this.allFloors.filter(floor => map[floor] && map[floor].length)
          this.floors = map
        }
      })
    },
    /**
         * 集散式,将数据解析为
         * {
         *  floor: [ {id, name, rooms: [id, name]} ]
         * }
         */
    genSepcialData (data) {
      const parents = data.filter(room => {
        return room.room_type === 2 && room.parent_ids.length > 0
      })
      const result = {}
      this.allFloors.forEach(floor => {
        result[floor] = []
      })
      parents.forEach(parentRoom => {
        result[parentRoom.floor].push({
          id: parentRoom.id,
          name: parentRoom.room_name,
          rooms: []
        })
      })
      data.forEach(item => {
        if (item.devices.length) this.hasDevice = true
        if (item.room_type === 1) {
          let noParentRoom = false
          result[item.floor].some(parentRoom => {
            if (item.parent_ids.includes(parentRoom.id)) {
              parentRoom.rooms.push({
                id: item.id,
                name: item.room_name
              })
              noParentRoom = false
              return true
            } else {
              noParentRoom = true
            }
          })
          if (!result[item.floor].length) noParentRoom = true
          if (noParentRoom) {
            result[item.floor].unshift({
              id: item.id,
              name: item.room_name
            })
          }
        }
        result[item.floor].sort((a, b) => {
          return a.name.localeCompare(b.name)
        })
      })
      for (let i in result) {
        if (result[i].length === 0) {
          this.allFloors = this.allFloors.filter(floor => +floor !== +i)
          delete result[i]
        }
      }
      this.isSpecialHome = true // 集散式房源
      this.floors = result
    },
    ok (lease_type) {
      if (this.homeId) {
        this.addHomes(lease_type, this.homeId.id)
      } else {
        this.addHomes(lease_type)
      }
    },
    editRoomName (v, index, indx) {
      if (this.homeId) {
        this.updateRoom(v.id, { room_name: v.name || v.room_name })
      }
    },
    fillZero (num) {
      return num <= 9 ? '0' + num : num
    },

    // 新增单个房间
    addRoom () {
      let names = this.formItem.roomName.trim().split(',')
      let floor = this.formItem.roomFloor
      let homeId = this.homeId.id

      const { pos, result } = this.validateName(names)
      if (!pos) {
        return
      } else {
        names = result
      }

      // console.log(names);

      let isInteger = /^-?\d+$/.test(floor)
      if (!isInteger || floor === 0) {
        this.$Message.error('请选择楼层')
        return
      }

      let params = {
        room_map: {
          [floor]: names
        }
      }

      util.log(homeId, params)

      http.request(this, api.room_create, [homeId], params, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('新增房间成功')
        this.getRooms(homeId)

        this.formItem.roomName = ''
        this.formItem.roomFloor = ''
        this.isAddRoomVisible = false
      })
    },

    validateName (names) {
      const { length } = names
      let pos = true
      if (!length) {
        this.$Message.error('房间名不能为空')
        pos = false
        return { pos, result: null }
      }

      for (let i = 0; i < length; i++) {
        const name = names[i]

        if (name === '公区') {
          this.$Message.error('房间名不能为公区')
          pos = false
          break
        }

        names[i] = { name }
      }

      if (!pos) {
        return { pos, result: null }
      } else {
        return { pos, result: names }
      }
    },

    cancelAddRoom () {
      this.formItem.roomName = ''
      this.formItem.roomFloor = ''
      this.isAddRoomVisible = false
    },

    // 删除房间
    deleteRoom (id, index, indx, ind) {
      this.isLoading = true
      http.request(
        this,
        api.room_del,
        [id],
        null,
        (res, err) => {
          if (err || !res) {
            this.isLoading = false
            return
          }
          this.getRooms(this.homeId.id)
          this.$Message.success('删除成功')
          this.isLoading = false
        },
        false
      )
    },
    // 楼层数组
    addFloors (start, total) {
      let ary = []
      for (let i = 1; i <= total; i++) {
        ary.push(this.fillZero(start + i))
      }
      return ary
    },
    replace (str) {
      let ary = [0]
      if (str) {
        str.replace(/\d+/gi, $0 => {
          ary.push(Number($0))
        })
      }
      // return str.split(' ').map(item => parseInt(item));
      return ary
    },
    // 生成房间
    addHouse () {
      this.hasRoomMiddle = this.modal3 && this.roomMiddle
      if (!this.floor) {
        this.$Message.error('请填写楼层数量')
        return
      }
      if (!this.room) {
        this.$Message.error('请填写每层房间数量')
        return
      }

      this.floor = parseInt(this.floor)
      this.room = parseInt(this.room)

      if (this.roomMiddle) {
        this.roomMiddle = parseInt(this.roomMiddle)
      }

      if (this.startFloor) {
        this.startFloor = parseInt(this.startFloor)
      }

      let ary = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N']
      let floor = this.floor
      let startFloor = this.startFloor || 1
      let rooms = this.room
      let passFloor = this.modal1 ? this.replace(this.passFloor) : []
      util.log('passFloor', passFloor)
      let roomMiddle = this.modal3 ? this.roomMiddle : 0
      // if (floor > 10) {
      //     this.$Message.error('最多创建10层')
      //     return
      // }
      // if (rooms > 100) {
      //     this.$Message.error('单层最多100间')
      //     return
      // }
      if (roomMiddle > 10) {
        this.$Message.error('最多拆分10间')
        return
      }
      let obj = {}
      while (Object.keys(obj).length < floor) {
        if (passFloor.indexOf(startFloor) >= 0 || startFloor === 0) {
          startFloor += 1
          continue
        }
        const padZeroStartFloor = this.padZero(startFloor)
        obj[startFloor] = []

        for (let i = 1; i <= rooms; i++) {
          let ii = i <= 9 ? '0' + i : i
          let room = {
            name: padZeroStartFloor + '' + ii,
            rooms: []
          }
          if (roomMiddle) {
            for (let j = 0; j < roomMiddle; j++) {
              let str = ary[j]
              room.rooms.push({
                name: padZeroStartFloor + '' + ii + '-' + str
              })
            }
          }
          obj[startFloor].push(room)
        }
        startFloor += 1
      }
      this.floors = obj
      util.log('====', roomMiddle, this.floors)
      if (this.getRoomsCount() > 1000) {
        this.$Message.info('最多添加1000个房间')
        this.floors = {}
      }
    },
    padZero (n) {
      if (String(n).length === 1) {
        return '0' + String(n)
      } else {
        return String(n)
      }
    },
    delHouse () {
      this.floors = {}
    },
    addTag () {
      this.tags.push(null)
      // console.log(this.tags);
    },
    delTag (index, indx, v) {
      if (this.isLoading) {
        this.$Message.info('操作中，请稍后..')
        return
      }
      if (this.homeId) {
        this.deleteRoom(v.id)
        // this.floors[index].splice(indx, 1)
      } else {
        this.floors[index].splice(indx, 1)
      }
      if (this.floors[index].length < 1) {
        delete this.floors[index]
      }
    },
    delTags (index, indx, ind, v) {
      if (this.homeId) {
        this.deleteRoom(v.id, index, indx, ind)
      } else {
        this.floors[index][indx]['rooms'].splice(ind, 1)
      }
      let flag = this.floors[index].every(item => {
        return item.rooms.length < 1
      })
      if (flag) delete this.floors[index]
    },
    setRoomChange (val) {
      this.clearChangeFloors()
      this.$set(val, 'toBeSave', true)
      this.$set(val, 'editable', true)
      this.$refs[val.id][0].focus()
    },
    // 更新房间
    updateRoom (roomId, room) {
      http.request(this, api.room_update, [roomId], room, (res, err) => {
        if (err || !res) {
          return
        }
        this.$Message.success('修改成功')
        this.refreshHomes()
      })
    },
    getRoomsCount () {
      let sum = 0
      Object.keys(this.floors).forEach(floor => {
        this.floors[floor].forEach(room => {
          const count = room.rooms && room.rooms.length > 0 ? room.rooms.length : 1
          sum += count
        })
      })
      return sum
    },

    checkRoomNames () {
      let result = ''
      Object.keys(this.floors).forEach(floor => {
        this.floors[floor].forEach(room => {
          if (room.name === '') result = '房间名不能为空'
          if (room.name === '公区') result = '房间名不能为公区'
        })
      })
      return result
    },

    // 添加房源
    addHomes (lease_type, id) {
      if (this.isLoading) {
        this.$Message.info('操作中，请稍后..')
        return
      }

      let areaInfo = this.areaInfo
      let params = {
        home_name: areaInfo.home_name,
        home_type: 2,
        street: areaInfo.street,
        block: areaInfo.block,
        district: areaInfo.area,
        city: areaInfo.city,
        province: areaInfo.province,
        country: '中国',
        number: areaInfo.doorNumber ? areaInfo.doorNumber : null,
        description: areaInfo.home_name
      }

      params.branch_id = areaInfo.branch_id ? areaInfo.branch_id : 0

      // util.log('params', params, this.floors);
      // return;
      if (id) {
        // 编辑房源
        this.isLoading = true
        const submiting = this.$Message.loading({
          content: '提交中...',
          duration: 0
        })
        http.request(this, api.home_update, [id], params, (res, err) => {
          this.isLoading = false
          submiting()
          if (err || !res) {
            return
          }
          this.$emit('update', id, true)
          this.$Message.success('修改成功')
        })
      } else {
        // 创建房源
        if (JSON.stringify(this.floors) === '{}' && !this.homeId) {
          this.$Message.error('请创建房间')
          return
        }

        if (this.getRoomsCount() > 1000) {
          this.$Message.info('最多添加1000个房间')
          return
        }

        const checkRoomResult = this.checkRoomNames()
        if (checkRoomResult) {
          this.$Message.info(checkRoomResult)
          return
        }
        this.isLoading = true
        const submiting = this.$Message.loading({
          content: '提交中...',
          duration: 0
        })

        params.lease_type = lease_type
        http.request(this, api.home_create, null, params, (res, err) => {
          this.isLoading = false
          if (err || !res) {
            submiting()
            return
          }
          let home_id = res['home_id']
          let obj = { room_map: this.floors }
          this.addRooms(home_id, obj, submiting)
        })
      }
    },

    // 添加房间
    addRooms (home_id, homes, submiting) {
      this.isLoading = true

      http.request(this, api.room_create, [home_id], homes, (res, err) => {
        if (typeof submiting === 'function') {
          submiting()
        }
        this.isLoading = false
        if (err || !res) {
          return
        }
        this.$Message.success('创建成功')
        this.$emit('update', 'focus')
      })
    },

    handleDeleteHome (homeId) {
      this.$emit('update', homeId)
    },

    refreshHomes () {
      this.getRooms(this.homeId.id)
    },

    getAllFloors () {
      return new Promise(resolve => {
        http.request(this, api.home_floors, [this.homeId.id], null, res => {
          this.existedFloors = res
          this.allFloors = res
          resolve()
        })
      })
    },

    cancelAddFloor () {
      this.isAddFloorVisible = false
      this.tempAddFloor = null
    },

    actionAddFloor () {
      let isInteger = /^-?\d+$/.test(this.tempAddFloor)

      if (!isInteger || this.tempAddFloor === 0) {
        this.$Message.error('请输入正确的楼层')
        return
      }

      if (this.allFloors.indexOf(this.tempAddFloor) > -1) {
        this.$Message.error('该楼层已存在')
        return
      }

      this.formItem.roomFloor = this.tempAddFloor
      this.changeFloor = this.tempAddFloor
      // this.isAddRoomVisible = true

      this.allFloors.push(this.tempAddFloor)
      this.$set(this.floors, this.tempAddFloor, [])
      this.isAddFloorVisible = false
      this.tempAddFloor = null
    },

    changeFloors () {
      // 批量修改楼层

      if (!this.changeFloor) {
        this.$Message.error('请选择楼层')
        return
      }
      if (this.isSpecialHome) {
        const rooms = this.getSpecialRooms()
        this.changeSpecialRooms(rooms)
      } else {
        this.changeNormalRooms()
      }
    },
    getSpecialRooms () {
      // 找出所有更改的房间
      const rooms = []
      for (let floor in this.floors) {
        this.floors[floor].forEach(parentRoom => {
          if (parentRoom.isChangeFloor) {
            rooms.push({
              id: parentRoom.id,
              floor: this.changeFloor
            })
            if (!parentRoom.rooms) return
            parentRoom.rooms.forEach(room => {
              rooms.push({
                id: room.id,
                floor: this.changeFloor
              })
            })
          }
        })
      }
      return rooms
    },
    /**
         * 批量更改集散式楼层
         * rooms: [{id, floor}]
         */
    async changeSpecialRooms (rooms) {
      if (!rooms.length) {
        this.$Message.error('请选择房间')
        return
      }

      try {
        await http.req(api.room_update_multiple, [this.homeId.id], { rooms })
        this.$Message.success('修改成功')
        this.refreshHomes()
      } catch (err) {
        console.log(err)
        this.$Message.error(err.message)
      }
    },
    changeNormalRooms () {
      let changeFloorRooms = []
      for (let floor in this.floors) {
        for (let index in this.floors[floor]) {
          let room = this.floors[floor][index]
          if (room.isChangeFloor) {
            changeFloorRooms.push({
              id: room.id,
              floor: this.changeFloor
            })
          }
        }
      }

      if (!changeFloorRooms.length) {
        this.$Message.error('请选择要修改楼层的房间')
        return
      }

      const params = {
        rooms: changeFloorRooms
      }

      http.request(this, api.room_update_multiple, [this.homeId.id], params, res => {
        this.$Message.success('修改成功')
        this.refreshHomes()
        util.log('~~~~~~~change floor', params)
      })
    },

    clearChangeFloors () {
      // 清空所选房间
      for (let floor in this.floors) {
        for (let index in this.floors[floor]) {
          let room = this.floors[floor][index]
          this.$set(room, 'isChangeFloor', false)
          this.$set(room, 'name', room.room_name)
          this.$set(room, 'toBeSave', false)
          // room.isChangeFloor = false
        }
      }
    },
    handleDeleteFloor (floor) {
      const newFloor = Number(floor)
      if (!this.existedFloors.includes(newFloor)) {
        delete this.floors[newFloor]
        this.allFloors = this.allFloors.filter(f => f !== newFloor)
        return
      }
      if (+floor === +this.allFloors[0]) {
        this.$Message.info('首层不能删除')
        return
      }
      this.$Modal.confirm({
        title: util.escapeHtml(`确定删除楼层${floor}?`),
        content: '楼层删除后，该楼层下的房间将自动列入首层',
        onOk: () => {
          this.deleteFloor(floor)
        }
      })
    },
    deleteFloor (floor) {
      const firstFloor = +this.allFloors[0]

      // 把要删的楼层改到首层
      this.editFloor(floor, firstFloor)
    },
    handleEditFloor (floor) {
      let newName = Number(floor)
      let currentFloor = Number(floor)
      this.$Modal.confirm({
        loading: true,
        render: h => {
          return h('InputNumber', {
            style: {
              width: '100%'
            },
            props: {
              value: newName,
              max: 99,
              min: 1
            },
            on: {
              input: val => {
                newName = val
              }
            }
          })
        },
        onOk: () => {
          if (Object.keys(this.floors).some(floor => Number(floor) === newName)) {
            this.$Message.info('已存在改楼层')
            this.$Modal.remove()
          } else if (!this.existedFloors.includes(currentFloor)) {
            const floors = [ newName, ...this.allFloors.filter(floor => floor !== currentFloor) ]
            floors.sort((a, b) => a - b)
            this.floors[newName] = this.floors[currentFloor]
            delete this.floors[currentFloor]
            this.allFloors = floors
            this.$Modal.remove()
          } else {
            this.editFloor(currentFloor, newName)
          }
        }
      })
    },
    editFloor (currentFloor, newName) {
      const currentFloorRooms = this.floors[currentFloor]
      const rooms = currentFloorRooms.map(item => {
        return {
          id: item.id,
          floor: newName
        }
      })
      http.request(this, api.room_update_multiple, [this.homeId.id], { rooms }, res => {
        if (res) {
          this.$Message.success('修改楼层成功')
          this.refreshHomes()
        }
      })
      this.$Modal.remove()
    }
  }
}
</script>

<style lang="less">
.flex-floor {
    flex-direction: column;
    width: 80px;
    margin-right: 15px;
    height: auto;
    background: #ffffff;
    align-items: center;
    text-align: center;
    justify-content: center;
    display: flex;
    border-left: 4px solid #05bac5;
}
.flex-room {
    flex: 1;
    margin-top: -15px;
}
.topBar {
    color: #1c2438;
    font-size: 18px;
    line-height: 50px;
    width: 100%;
    height: 50px;
    background: #efeff1;
    padding-left: 10px;
    border-left: 5px solid #05bac5;
}
.range {
    margin-bottom: 20px;
}
.floor-item {
    display: flex;
    background: #efeff1;
    margin: 0px;
    padding: 15px;
    border-radius: 4px;
    margin-top: 10px;
}
.marginTopItem {
    margin-top: 20px;
}
.btn-in-top-add {
    border-radius: 0;
    margin-right: 10px;
}
.room-item-wrapper {
    .ivu-input-group-append {
        padding: 6px 12px;
    }
    .room-operate-btn {
        border:1px solid #05bac5;
        color: #05bac5;
        display: none;
    }
}
.del-room-icon {
    font-size: 24px;
}
.room-item-wrapper:hover {
    .room-operate-btn {
        display: block;
    }
    .ivu-input-group-append {
        cursor: pointer;
        color: #fff;
        background-color: #05bac5;
    }
}
</style>
